package com.jketing.utils;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;

import org.springframework.web.multipart.MultipartFile;

public class ImageUtil {

	/**
	 * 将图片文件转换后输出
	 * @throws IOException 
	 */
	public static void zoomImage(InputStream input, String tagFileName,
			int width, int height) throws IOException {
		BufferedImage bi = ImageIO.read(input);
		BufferedImage tag = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_RGB);
		tag.getGraphics().drawImage(bi, 0, 0, width, height, null);
		ImageIO.write(tag, "jpg", new File(tagFileName));
	}
	
	public static byte[] getPhotoBytes(MultipartFile file, long countKB, int width,
			int height) throws IOException {
		byte b[] = null;
		if (file.getSize() >= countKB * 1024) {
			String folder = System.getProperty("java.io.tmpdir");
			String outFileName = "upload.jpg";
			File outFile = null;
			InputStream input = null;
			zoomImage(file.getInputStream(), folder + outFileName, width, height); // 将图片文件转换后输出
			outFile = new File(folder + outFileName);
			input = new FileInputStream(outFile);
			b = new byte[(int)outFile.length()];
			input.read(b);
			input.close();
			outFile.delete();
		}else {
			b = file.getBytes();
		}
		return b;
	}
}
